<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="产品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['dishes:dishes:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['dishes:dishes:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['dishes:dishes:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="dishesList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品ID" align="center" prop="dishId" />
      <el-table-column label="产品名称" align="center" prop="name" />
      <el-table-column label="产品图片" align="center" prop="picturePath">
        <template #default="scope">
          <img
            style="width: 100px; height: 100px"
            :src="baseUrl + scope.row.picturePath"
            alt=""
          />
        </template>
      </el-table-column>
      <el-table-column label="适用人群" align="center" prop="description" />
      <el-table-column label="产品价格" align="center" prop="price" />
      <el-table-column label="产品类别" align="center" prop="categoryId">
        <template #default="scope">
          <span>{{ findCategoryById(scope.row.categoryId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="产品期限" align="center" prop="nutritionalInfo" />
      <el-table-column label="是否为推荐产品" align="center" prop="isFeatured">
        <template #default="scope">
          <span>{{ scope.row.isFeatured == "0" ? "否" : "是" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['dishes:dishes:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['dishes:dishes:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="dishesRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="适用人群" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="产品价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入产品价格" />
        </el-form-item>
        <el-form-item label="产品类别" prop="categoryId">
          <el-select
            v-model="form.categoryId"
            placeholder="请选择产品类别"
            size="default"
          >
            <el-option
              v-for="item in categoriesList"
              :key="item.value"
              :label="item.name"
              :value="item.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="保险期限" prop="nutritionalInfo">
          <el-input
            v-model="form.nutritionalInfo"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="是否推荐" prop="isFeatured">
          <el-select
            v-model="form.isFeatured"
            placeholder="请选是否为推荐菜"
            size="default"
          >
            <el-option key="1" label="是" value="1" />
            <el-option key="0" label="否" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="产品图片" prop="picturePath">
          <ImageUploader
            :limit="1"
            :fileSize="2"
            :fileType="['png', 'jpg']"
            @update:modelValue="handleImageUpdate"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Dishes">
import {
  listDishes,
  getDishes,
  delDishes,
  addDishes,
  updateDishes,
} from "@/api/dishes/dishes";
import { listCategories } from "@/api/categories/categories";
import { uploadAvatar } from "@/api/system/user";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import ImageUploader from "@/components/ImageUpload";

const { proxy } = getCurrentInstance();
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const dishesList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10000,
    name: null,
    description: null,
    price: null,
    categoryId: null,
    nutritionalInfo: null,
    isFeatured: null,
  },
  rules: {
    name: [{ required: true, message: "产品名称不能为空", trigger: "blur" }],
    price: [{ required: true, message: "产品价格不能为空", trigger: "blur" }],
    categoryId: [
      { required: true, message: "请选择产品类别", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

const categoriesList = ref([]); //产品分类列表
const imageUrl = ref("");
const handleImageUpdate = (images) => {
  // 处理更新后的图片列表
  form.value.picturePath = images;
};


/** 上传图片 */
function uploadImg() {
  proxy.$refs.cropper.getCropBlob((data) => {
    let formData = new FormData();
    formData.append("avatarfile", data, options.filename);
    uploadAvatar(formData).then((response) => {
      open.value = false;
      options.img = import.meta.env.VITE_APP_BASE_API + response.imgUrl;
      userStore.avatar = options.img;
      proxy.$modal.msgSuccess("修改成功");
      visible.value = false;
    });
  });
}

// 获取产品类别
const getCategoriesList = () => {
  listCategories().then((response) => {
    categoriesList.value = response.rows;
  });
};

getCategoriesList();

// 根据id查找产品类别
const findCategoryById = (id) => {
  const current = categoriesList.value.filter((v) => v.categoryId === id)[0];
  return current.name;
};

/** 查询产品管理列表 */
function getList() {
  loading.value = true;
  listDishes(queryParams.value).then((response) => {
    dishesList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    dishId: null,
    name: null,
    description: null,
    price: null,
    categoryId: null,
    nutritionalInfo: null,
    isFeatured: null,
    picturePath: null,
    createdAt: null,
    updatedAt: null,
  };
  proxy.resetForm("dishesRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.dishId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  imageUrl.value = "";
  open.value = true;
  title.value = "添加产品";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  console.log(form.value);

  imageUrl.value = form.value.picturePath;
  reset();
  const _dishId = row.dishId || ids.value;
  getDishes(_dishId).then((response) => {
    form.value = response.data;
    form.value.isFeatured = response.data.isFeatured.toString();
    open.value = true;
    title.value = "修改产品";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["dishesRef"].validate((valid) => {
    if (valid) {
      if (form.value.dishId != null) {
        updateDishes(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDishes(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _dishIds = row.dishId || ids.value;
  proxy.$modal
    .confirm('是否确认删除产品理编号为"' + _dishIds + '"的数据项？')
    .then(function () {
      return delDishes(_dishIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "dishes/dishes/export",
    {
      ...queryParams.value,
    },
    `dishes_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>

<style lang="less" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>